/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 23
 * Time: 14:27
 */
//牛客 删除链表的倒数第n个节点
public class Solution4 {
    public ListNode removeNthFromEnd (ListNode head, int n) {
        if(head == null) return null;
        ListNode dummyNode = new ListNode(-1);//避免头结点的分类讨论，如头结点有可能被删除
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0; i < n - 1; i++) {
            fast = fast.next;
        }
        while(fast.next != null) {
            fast = fast.next;
            pre = slow;
            slow = slow.next;
        }
        pre.next = slow.next;
        return dummyNode.next;
    }
}
